﻿using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.TeamFoundation;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Common;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TeamFoundation;

namespace Solutions4u.BuildProcessCommands
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the 
    /// IVsPackage interface and uses the registration attributes defined in the framework to 
    /// register itself and its components with the shell.
    /// </summary>
    // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
    // a package.
    [PackageRegistration(UseManagedResourcesOnly = true)]
    // This attribute is used to register the informations needed to show the this package
    // in the Help/About dialog of Visual Studio.
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    // This attribute is needed to let the shell know that this package exposes some menus.
    [ProvideMenuResource("Menus.ctmenu", 1)]
    [Guid(GuidList.guidBuildProcessCommandsPkgString)]
    // Autoload with Team Explorer
    [ProvideAutoLoad("{4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}")]
    public sealed class BuildProcessCommandsPackage : Package
    {
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require 
        /// any Visual Studio service because at this point the package object is created but 
        /// not sited yet inside Visual Studio environment. The place to do all the other 
        /// initialization is the Initialize method.
        /// </summary>
        public BuildProcessCommandsPackage()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
        }

        /// <summary>
        /// Gets the TeamExplorer.
        /// </summary>
        private IVsTeamExplorer TeamExplorer
        {
            get
            {
                IVsTeamExplorer service = this.GetService(typeof(IVsTeamExplorer)) as IVsTeamExplorer;
                if (service != null)
                {
                    return service;
                }
                else
                {
                    throw new TeamFoundationServiceUnavailableException("IVsTeamExplorer");
                }
            }
        }

        // Overriden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initilaization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Trace.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if ( null != mcs )
            {
                // Create the command for the export menu item.
                CommandID menuExportCommandID = new CommandID(GuidList.guidBuildProcessCommandsCmdSet, (int)PkgCmdIDList.cmdIdExportProcessFromBuildDefinition);
                MenuCommand menuItemExport = new MenuCommand(ExecuteExportCommand, menuExportCommandID );
                mcs.AddCommand( menuItemExport);

                // Create the command for the import menu item.
                CommandID menuImportCommandID = new CommandID(GuidList.guidBuildProcessCommandsCmdSet, (int)PkgCmdIDList.cmdIdImportProcessToBuildDefinition);
                MenuCommand menuItemImport = new MenuCommand(ExecuteImportCommand, menuImportCommandID);
                mcs.AddCommand(menuItemImport);
            }
        }
        #endregion
                
        /// <summary>
        /// Exports the ProcessParameters from the selected BuildDefinition (Node)
        /// </summary>
        private void ExecuteExportCommand(object sender, EventArgs e)
        {
            IBuildDefinition buildDefinition = this.GetSelectedBuildDefinition();

            if (buildDefinition != null)
            {
                string processParameters = buildDefinition.ProcessParameters;

                SaveFileDialog saveBuildProcessDialog = new SaveFileDialog();
                saveBuildProcessDialog.Filter = @"XAML File|*.xaml|TEXT File|*.txt";
                saveBuildProcessDialog.FileName = buildDefinition.Name + ".BuildProcess";
                saveBuildProcessDialog.Title = @"Save the Build Process File";
                DialogResult dialogResult = saveBuildProcessDialog.ShowDialog();

                if (dialogResult == DialogResult.OK)
                {
                    StringBuilder sb = new StringBuilder(processParameters);
                    using (StreamWriter sw = new StreamWriter(saveBuildProcessDialog.OpenFile(), Encoding.UTF8))
                    {
                        sw.Write(processParameters);
                    }
                }
            }
        }

        /// <summary>
        /// Gets the selected build definition.
        /// </summary>
        private IBuildDefinition GetSelectedBuildDefinition()
        {
            IVsTeamExplorer teamExplorer = this.TeamExplorer;

            if (teamExplorer != null)
            {
                IVsMultiItemSelect multiItemSelect = null;
                uint num = 0;
                object obj = null;
                IntPtr zero = new IntPtr(0);

                if (teamExplorer.TeamExplorerWindow.GetCurrentSelection(out zero, out num, out multiItemSelect) == 0)
                {
                    ProjectContext projectContext = teamExplorer.GetProjectContext();

                    IVsHierarchy objectForIUnknown = (IVsHierarchy)Marshal.GetObjectForIUnknown(zero);

                    if (objectForIUnknown.GetProperty(num, -2012, out obj) == 0)
                    {
                        Marshal.Release(zero);
                        zero = IntPtr.Zero;

                        TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(projectContext.DomainUri));

                        IBuildServer service = teamProjectCollection.GetService<IBuildServer>();
                        if (service != null)
                        {
                            return service.GetBuildDefinition(projectContext.ProjectName, obj.ToString());
                        }
                        else
                        {
                            throw new ApplicationException("Failed to get a reference to IBuildServer");
                        }
                    }
                    else
                    {
                        Marshal.Release(zero);

                        throw new ApplicationException("Failed to get currently selected item");
                    }
                }
                else
                {
                    throw new ApplicationException("Failed to get the selected build definition.");
                }
            }
            else
            {
                throw new ApplicationException("Failed to get the Team Explorer service.");
            }
        }

        /// <summary>
        /// Imports a ProcessParameters File to the selected BuildDefinition (Node)
        /// </summary>
        private void ExecuteImportCommand(object sender, EventArgs e)
        {
            IBuildDefinition buildDefinition = this.GetSelectedBuildDefinition();

            OpenFileDialog openBuildProcessDialog = new OpenFileDialog();
            openBuildProcessDialog.Filter = @"XAML File|*.xaml|TEXT File|*.txt";
            openBuildProcessDialog.Title = @"Import the Build Process File to " + buildDefinition.Name;

            if (openBuildProcessDialog.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(openBuildProcessDialog.FileName);
                string processParameters = sr.ReadToEnd();
                sr.Close();

                if (processParameters.Length > 0)
                {
                    buildDefinition.ProcessParameters = processParameters;
                    buildDefinition.Save();
                }
            }
        }

    }
}
